package dao

import (
	"log"
	"testhttp/datasource"
	"time"
)

type Member struct {
	// Id          string `json:""` //
	MemName    string    `json:"username"`      //姓名
	MemPhone   string    `json:"userphone"`     //电话
	Sheng      string    `json:"province"`      //省
	Shi        string    `json:"city"`          //市
	Qu         string    `json:"district"`      //区/县
	XiangxiDz  string    `json:"detailaddress"` //详细地址
	WanzhDz    string    `json:"fulladdress"`   //完整地址
	MemUid     string    `json:"mem_uid"`       //客户uid
	Remark     string    `json:"remark"`        //备注
	CreateTime time.Time `json:"createat"`      //创建时间
	UpdateTime time.Time `json:"updateat"`      //更新时间
	IsDeleted  int       `json:"is_deleted"`    //默认0，未删除，1已删除。
}

func GetMems(phone string) bool { //用于验证这个用户的电话号码，在未删除的信息中是否已存在。
	te := new(Member)
	res, err := datasource.InstanceMaster().Where("mem_phone =? and is_deleted =?", phone, 0).Get(te)
	if err != nil {
		log.Print("Error GetMems():", err)
	}
	return res
}

func ListMember(searchparams string, pagesize, page int) ([]Member, int64) {

	uniq := new(Member)
	res := make([]Member, 0)
	offset := (page - 1) * pagesize

	// if goods == "" && shop == "" {
	count, err1 := datasource.InstanceMaster().Where(searchparams).Count(uniq)
	if err1 != nil {
		log.Print("Error ListMember():", err1)
	}

	err := datasource.InstanceMaster().Where(searchparams).Limit(pagesize, offset).Find(&res)
	if err != nil {
		log.Print("Error ListMember():", err)
	}

	return res, count
}

func InsertMembers(member []Member) {
	affected, err := datasource.InstanceMaster().Insert(member)
	log.Printf("Success! %d records insert.\n", affected)
	if err != nil {
		log.Print("Error InsertMembers():", err)
	}
}

func UpdateMembers(member []Member) {
	for x := 0; x < len(member); x++ {
		// log.Print("Debug uid:", member[x].MemUid)
		affected, err := datasource.InstanceMaster().Where("mem_uid = ?", member[x].MemUid).Update(member[x])
		log.Printf("%d records updated.\n", affected)
		if err != nil {
			log.Print("Error UpdateMembers():", err)
		}
	}
}

func ViewMember(uid string) []Member {

	res := make([]Member, 0)
	err := datasource.InstanceMaster().Where("mem_uid =?", uid).Find(&res)
	if err != nil {
		log.Print("Error ListMember():", err)
	}
	return res
}
